package org.cuatrovientos.onceuponatime;

import java.io.IOException;




import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;






/**
 * Servlet implementation class Home
 * @author Daniel Cobo
 */
@WebServlet("/Home")
public class Home extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Home() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		receiveTales(request, response);
	}
/**
 * Receives all the tales from the database
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 */
	private void receiveTales(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String tales = null;
		try {
			tales = getTales();
		} catch (SQLException e) {

			e.printStackTrace();
		}
		request.setAttribute("tales", tales);


		this.getServletContext().getRequestDispatcher("/home.jsp")
		.forward(request, response);
	}
	/**
	 * gets all tales from database
	 * @return
	 * @throws SQLException 
	 */
	private String getTales() throws SQLException {
		String allTales = "";

		String urlcon= "jdbc:mysql://localhost:3306/onceupon";
		ResultSet resultset = null;
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(urlcon, "root", "");
			Statement stat = conn.createStatement();
			resultset =	stat.executeQuery("select * from tale");
			while(resultset.next()){
				allTales += resultset.getString("title") + " <a href='#' onClick='fun(" + resultset.getString("id")  + ")'>Delete </a> <a href=\"Update?id="+resultset.getString("id")+"\">Update </a> <br/>";
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		resultset.close();
		conn.close();


		return allTales;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		receiveTales(request, response);
	}

}
